<template>
  <div class="mod-config">
    <div v-if="member">
      <el-form :inline="true" :model="dataForm" @keyup.enter.native="search()" ref="dataForm">
        <el-form-item label="是否已贴标签：">
          <el-select v-model="dataForm.hasLabel" placeholder="请选择">
            <el-option
              v-for="item in useroption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签：">
          <el-select v-model="dataForm.label" placeholder="请选择标签">
            <el-option
              v-for="item in useroption1"
              :key="item.id"
              :label="item.labelName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="等级：">
          <el-select v-model="dataForm.level" placeholder="请选择等级">
            <el-option
              v-for="item in useroption2"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="兑换资源状态：">
          <el-select v-model="dataForm.status" placeholder="请选择">
            <el-option
              v-for="item in useroption3"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model="dataForm.nickname" placeholder="昵称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="dataForm.phone" placeholder="手机号"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search()">查询</el-button>
          <el-button type="primary" @click="download" :loading="downloading">下载</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="dataList"
        border
        v-loading="dataListLoading"
        style="width: 100%;"
      >
        <el-table-column prop="id" header-align="center" align="center" label="uid"></el-table-column>
        <el-table-column header-align="center" align="center" label="头像">
          <template slot-scope="scope">
            <img :src="scope.row.avatar" alt="">
          </template>
        </el-table-column>
        <el-table-column prop="nickname" header-align="center" align="center" label="昵称"></el-table-column>
        <el-table-column prop="phone" header-align="center" align="center" label="手机号"></el-table-column>
        <el-table-column prop="wxNumber" header-align="center" align="center" label="微信号"></el-table-column>
        <el-table-column prop="uid" header-align="center" align="center" label="二维码">
          <template slot-scope="scope">
            <img v-if="scope.row.wxQrcode" :src="scope.row.codeImg" style="width:40px;height:40px;">
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column prop="currentPoint" header-align="center" align="center" label="可用积分"></el-table-column>
        <el-table-column prop="totalPoint" header-align="center" align="center" label="总获得积分"></el-table-column>
        <el-table-column prop="lastMonthPoint" header-align="center" align="center" label="上月获得积分"></el-table-column>
        <el-table-column prop="level" header-align="center" align="center" label="等级"></el-table-column>
        <el-table-column prop="bookId" header-align="center" align="center" label="是否已贴标签">
          <template slot-scope="scope">
            {{ scope.row.hasLabel === 1?'已贴':'' }}
            {{ scope.row.hasLabel === 0?'未贴':'' }}
            {{ scope.row.hasLabel === 2?'未达资格':'' }}
          </template>
        </el-table-column>
        <el-table-column prop="appLabels" header-align="center" align="center" label="标签"></el-table-column>
        <el-table-column prop="releaseTime" header-align="center" align="center" label="解禁时间"></el-table-column>
        <el-table-column prop="bookId" header-align="center" align="center" label="兑换资源状态">
          <template slot-scope="scope">
            {{ scope.row.status === 1?'正常':'' }}
            <el-button v-if="scope.row.status === 3" type="text" size="small" @click="getResource(scope.row.userId, 3)">
              禁止兑换
            </el-button>
            <el-button v-if="scope.row.status === 4" type="text" size="small" @click="getResource(scope.row.userId, 4)">
              取消标签
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="bookId" header-align="center" align="center" label="积分明细">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="lookOrCheck(scope.row.userId)">查看</el-button>
          </template>
        </el-table-column>
        <el-table-column fixed="right" header-align="center" align="center" label="操作" width="150px">
          <template slot-scope="scope">
            <div>
              <el-button type="text" size="small" @click="setNum(scope.row.userId, 1)">加分</el-button>
              <el-button type="text" size="small" @click="setNum(scope.row.userId, 2)">减分</el-button>
            </div>
            <div v-if="scope.row.hasLabel === 0" class="inineBlock">
              <el-button type="text" size="small" @click="stickLabel(scope.row.userId)">贴标签</el-button>
            </div>
            <div v-if="scope.row.hasLabel === 1" class="inineBlock">
              <el-button type="text" size="small" @click="setCancel(scope.row.userId)">取消标签</el-button>
              <el-button type="text" size="small" @click="stickLabel(scope.row.userId, scope.row.appLabels)">更改标签
              </el-button>
              <el-button v-if="scope.row.status !== 3" type="text" size="small" @click="setForbid(scope.row.userId)">
                禁止兑换
              </el-button>
              <el-button v-if="scope.row.status === 3" type="text" size="small" @click="setRemove(scope.row.userId)">
                解除禁止
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="pageIndex"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper"
      ></el-pagination>

      <!--贴标签操作s-->
      <el-dialog
        :close-on-click-modal="false"
        :visible.sync="visible1"
        title="选择标签"
      >
        <el-form
          :model="dataForm1"
          ref="dataForm1"
          label-width="150px"
          :rules="rules"
        >
          <el-form-item label="请选择标签:" prop="labelIds">
            <el-select v-model="dataForm1.labelIds" multiple placeholder="请选择">
              <el-option
                v-for="item in appLabel"
                :key="item.id"
                :label="item.labelName"
                :value="item.id">
              </el-option>
            </el-select>
            <div>可以多选</div>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="visible1 = false">取消</el-button>
          <el-button type="primary" @click="setLabel">确定</el-button>
        </span>
      </el-dialog>
      <!--贴标签操作e-->

      <!--兑换资源状态查看s-->
      <el-dialog
        :close-on-click-modal="false"
        :visible.sync="visibleResource"
        title="详情"
      >
        <div>
          <el-row :gutter="20" class="margin_10">
            <el-col :span="6" class="text_r">{{ resourceType === '3' ? '禁止兑换理由：' : '取消标签理由：' }}</el-col>
            <el-col :span="18">{{ forbidDetail.actionReason }}</el-col>
          </el-row>
          <el-row :gutter="20" class="margin_10">
            <el-col :span="6" class="text_r">{{ resourceType === '3' ? '禁止兑换描述：' : '取消标签描述：' }}</el-col>
            <el-col :span="18">{{ forbidDetail.actionDesc }}</el-col>
          </el-row>
          <el-row :gutter="20" class="margin_10">
            <el-col :span="6" class="text_r">图片说明：</el-col>
            <el-col :span="18">
              <div class="imgList">
                <div v-for="item in actionImages"><img :src="item" alt=""></div>
              </div>
            </el-col>
          </el-row>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="visibleResource = false">返回</el-button>
        </span>
      </el-dialog>
      <!--兑换资源状态查看e-->

      <!-- 其他操作弹窗 -->
      <other-dialog ref="otherDialog" @refreshDataList="getDataList"></other-dialog>
    </div>

    <!--积分明细-->
    <integral-list v-else ref="integralList" @goBack="showMember"></integral-list>
  </div>
</template>

<script>
  import OtherDialog from './otherDialog'
  import IntegralList from './integralList'
  import QRCode from "qrcode";

  export default {
    data() {
      return {
        downloading: false,
        member: true,
        visibleIntegralList: false,
        dataForm1: {
          labelIds: []
        },
        rules: {
          labelIds: [
            {required: true, message: '请选择标签', trigger: 'blur'}
          ],
        },
        zanConfig: 0,
        visible1: false,
        useroption: [
          {
            value: null,
            label: '全部'
          },
          {
            value: '0',
            label: '未贴'
          },
          {
            value: '1',
            label: '已贴'
          },
          {
            value: '2',
            label: '未达资格'
          }
        ],
        useroption1: [],
        useroption2: [
          {
            value: null,
            label: '全部'
          },
          {
            value: '1',
            label: '青铜'
          },
          {
            value: '2',
            label: '白银'
          },
          {
            value: '3',
            label: '黄金'
          },
          {
            value: '4',
            label: '钻石'
          }
        ],
        useroption3: [
          {
            value: null,
            label: '全部'
          },
          {
            value: '1',
            label: '正常'
          },
          {
            value: '2',
            label: '禁止兑换'
          },
          {
            value: '3',
            label: '取消标签'
          }
        ],
        dataForm: {
          reviewState: null,
          isPublic: '1',
          label: null
        },
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        appLabel: [],
        visibleResource: false,
        forbidDetail: {},
        actionImages: [],
        resourceType: ''
      }
    },
    components: {
      OtherDialog,
      IntegralList
    },
    activated() {
      this.getAppLabel()
      this.getDataList()
    },
    methods: {
      search() {
        this.pageIndex = 1
        this.getDataList()
      },
      getAppLabel() {
        this.$http({
          url: this.$http.adornUrl('/point/applabel/list'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.appLabel = data.appLabelList
            this.useroption1 = [{id: null, labelName: '全部'}, ...data.appLabelList]
          }
        })
      },
      // 获取数据列表
      getDataList() {
        this.dataListLoading = true
        this.dataForm.page = this.pageIndex
        this.dataForm.limit = this.pageSize
        this.$http({
          url: this.$http.adornUrl('/point/userRewardPoint/list'),
          method: 'get',
          params: this.$http.adornParams(this.dataForm)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$refs['dataForm'].resetFields()
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
            let len = data.page.list.length;
            for (let i = 0; i < len; i++) {
              let codeUrl = this.dataList[i].wxQrcode || "";
              let opts = {
                errorCorrectionLevel: "H",
                type: "image/jpeg",
                rendererOpts: {
                  quality: 0.3
                }
              };
              QRCode.toDataURL(codeUrl, opts, (err, url) => {
                this.dataList[i].codeImg = url;
              });
            }
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // 贴标签
      stickLabel(id, labels) {
        this.dataForm1.labelIds = []
        this.dataForm1.userId = id
        this.visible1 = true
        // 更改标签时获取标签展示
        if (labels) {
          const labelArr = labels.split(',')
          const checkLabel = this.appLabel.filter(item => {
            return labelArr.some(it => it === item.labelName)
          })
          checkLabel.map(item => {
            this.dataForm1.labelIds.push(item.id)
          })
        }
      },
      setLabel() {
        const obj = {
          userId: this.dataForm1.userId,
          labelIds: this.dataForm1.labelIds.toString()
        }
        this.$refs['dataForm1'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl('/point/userRewardPoint/saveOrUpdateLabel'),
              method: 'get',
              params: this.$http.adornParams(obj)
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.visible1 = false
                this.$message.success('操作成功')
                this.search()
              }
            })
          } else {
            return false;
          }
        });
      },
      // 加/减分
      setNum(id, type) {
        this.$nextTick(() => {
          this.$refs.otherDialog.initNum(id, type)
        })
      },
      // 取消标签
      setCancel(id) {
        this.$nextTick(() => {
          this.$refs.otherDialog.initCancel(id)
        })
      },
      // 禁止兑换
      setForbid(id) {
        this.$nextTick(() => {
          this.$refs.otherDialog.initForbid(id)
        })
      },
      getResource(id, type) {
        this.resourceType = type
        this.visibleResource = true
        const obj = {
          userId: id,
          status: type
        }
        this.$http({
          url: this.$http.adornUrl('/point/userRewardPoint/getUserStatusDetail'),
          method: 'get',
          params: this.$http.adornParams(obj)
        }).then(({data}) => {
          this.forbidDetail = data
          this.actionImages = data.actionImages ? JSON.parse(data.actionImages) : []
        })
      },
      // 解除禁止
      setRemove(id) {
        this.$confirm('是否确定解除禁止?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/point/userRewardPoint/cancelForbid'),
            method: 'get',
            params: this.$http.adornParams({userId: id})
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.visible1 = false
              this.$message.success('操作成功')
              this.search()
            }
          })
        }).catch(() => {

        })
      },
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 新增 / 修改
      lookOrCheck(id) {
        this.member = false
        this.$nextTick(() => {
          this.$refs.integralList.initIntegral(id)
        })
      },
      showMember() {
        this.member = true
      },
      download() {
        this.downloading = true
        this.dataForm.page = this.pageIndex
        this.dataForm.limit = this.pageSize
        this.$http({
          url: this.$http.adornUrl("/point/userRewardPoint/download"),
          method: "get",
          params: this.$http.adornParams(this.dataForm),
          headers: {
            "Content-Type": "application/json; application/octet-stream"
          },
          responseType: "arraybuffer"
        }).then(({data}) => {
          this.downloading = false
          const blob = new Blob([data], {type: "application/vnd.ms-excel"});
          const downloadElement = document.createElement("a");
          const href = window.URL.createObjectURL(blob);
          downloadElement.href = href;
          downloadElement.download = "会员积分列表.xls";
          document.body.appendChild(downloadElement);
          downloadElement.click();
          document.body.removeChild(downloadElement); // 下载完成移除元素
          window.URL.revokeObjectURL(href); // 释放掉blob对象
        }).catch(error => {
          console.log(error)
          this.downloading = false
          this.$message.error('由于请求下载条数过多请求超时，请根据搜索条件降低下载条数～')
        });
      }
    }
  }
</script>
<style>
  .margin_10 {
    margin-bottom: 10px;
  }

  .text_r {
    text-align: right;
    padding-right: 15px;
  }

  .inineBlock {
    display: inline-block;
  }

  img {
    width: 100%;
    height: auto;
  }

  .imgList {
    display: flex;
    flex-wrap: wrap;
  }

  .imgList > div {
    width: 80px;
    margin: 5px 15px 5px 0;
  }
</style>
